package com.firefly.admin.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.enums.DataPermissionRangeEnum;
import com.firefly.admin.common.enums.ResultCodeEnum;
import com.firefly.admin.common.enums.SensitiveTypeEnum;
import com.firefly.admin.common.utils.*;
import com.firefly.admin.common.vo.LoginUser;
import com.firefly.admin.common.vo.Result;
import com.firefly.admin.system.entity.FySystemMenu;
import com.firefly.admin.system.service.FySystemOrganizationService;
import com.firefly.admin.system.service.FySystemUserRoleService;
import com.firefly.admin.system.service.FySystemUserService;
import com.firefly.admin.system.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.firefly.admin.system.entity.FySystemOrganization;
import com.firefly.admin.system.entity.FySystemUser;
import com.firefly.admin.system.entity.FySystemUserRole;
import com.firefly.admin.system.mapper.FySystemUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FySystemUserServiceImpl implements FySystemUserService {
    @Autowired
    private FySystemUserMapper fySystemUserMapper;
    @Autowired
    private FySystemUserRoleService fySystemUserRoleService;
    @Autowired
    private FySystemOrganizationService fySystemOrganizationService;

    /**
     * 通过用户名查询管理员账号信息
     *
     * @param userName 管理员用户名
     * @return 管理员账号列表
     */
    @Override
    public List<FySystemUser> getSystemUserByUserName(String userName) {
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getUserName, userName);
        return fySystemUserMapper.selectList(queryWrapper);
    }

    /**
     * 获取系统管理员信息接口
     *
     * @param userId 系统管理员ID
     * @return 系统管理员信息
     */
    @Override
    public Result<FySystemUser> getSystemUser(Long userId) {
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        if (fySystemUser == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
        }
        HttpServletRequest request = RequestUtil.getRequest();
        String localIp = IpUtil.getLocalIp(request);
        fySystemUser.setLoginIp(localIp);
        String loginAddress = AreaAddressUtil.getAreaAddress(localIp);
        fySystemUser.setLoginAddress(loginAddress);
        return Result.success(fySystemUser);
    }

    /**
     * 系统管理员信息新增接口
     *
     * @param fySystemUser 系统管理员信息
     * @return 新增结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<FySystemUser> add(FySystemUser fySystemUser) {
        if (fySystemUser == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        ResultCodeEnum resultCodeEnum = checkUserParam(fySystemUser);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemUserMapper.insert(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.ADD_EXCEPTION);
        }
        return Result.success(fySystemUser);
    }

    /**
     * 系统管理员信息编辑接口
     *
     * @param fySystemUser 系统管理员信息
     * @return 编辑结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<FySystemUser> update(FySystemUser fySystemUser) {
        if (fySystemUser == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long userId = fySystemUser.getUserId();
        if (userId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemUser systemUser = fySystemUserMapper.selectById(userId);
        if (systemUser == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
        }
        ResultCodeEnum resultCodeEnum = checkUserParam(fySystemUser);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemUserMapper.updateById(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        return Result.success(fySystemUser);
    }

    /**
     * 系统管理员信息删除接口
     *
     * @param userIds 管理员ID
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> delete(Long[] userIds) {
        if (userIds == null || userIds.length <= 0) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        for (Long userId : userIds) {
            FySystemUser systemUser = fySystemUserMapper.selectById(userId);
            if (systemUser == null) {
                return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
            }
            int rows = fySystemUserMapper.deleteById(userId);
            if (rows <= 0) {
                return Result.getResult(ResultCodeEnum.DELETE_EXCEPTION);
            }
            List<FySystemUserRole> userRoleList = fySystemUserRoleService.selectByUserId(userId);
            if (!CollectionUtils.isEmpty(userRoleList)) {
                //删除原有角色
                int deleteRows = fySystemUserRoleService.deleteByUserId(userId);
                if (deleteRows <= 0) {
                    return Result.getResult(ResultCodeEnum.DELETE_USER_ROLES_EXCEPTION);
                }
            }
        }
        return Result.success();
    }

    /**
     * 分页查询系统管理员接口
     *
     * @param systemUserQueryVo 系统管理员查询条件
     * @return 管理员信息列表
     */
    @Override
    public Result<Page<FySystemUser>> getSystemUserList(SystemUserQueryVo systemUserQueryVo) {
        log.info("###########FySystemUserServiceImpl getSystemUserList param = {}", JSONObject.toJSONString(systemUserQueryVo));
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(systemUserQueryVo.getUserName()), FySystemUser::getUserName, systemUserQueryVo.getUserName());
        queryWrapper.like(StringUtils.isNotBlank(systemUserQueryVo.getMobile()), FySystemUser::getMobile, systemUserQueryVo.getMobile());
        queryWrapper.like(StringUtils.isNotBlank(systemUserQueryVo.getRealName()), FySystemUser::getRealName, systemUserQueryVo.getRealName());
        queryWrapper.eq(StringUtils.isNotBlank(systemUserQueryVo.getUserStatus()), FySystemUser::getUserStatus, systemUserQueryVo.getUserStatus());
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        queryWrapper.orderByDesc(FySystemUser::getUserId);
        Page<FySystemUser> page = new Page<>(systemUserQueryVo.getPage(), systemUserQueryVo.getLimit());
        Page<FySystemUser> systemUserPage = fySystemUserMapper.selectPage(page, queryWrapper);
        List<FySystemUser> systemUserList = systemUserPage.getRecords();
        if (!CollectionUtils.isEmpty(systemUserList)) {
            for (FySystemUser fySystemUser : systemUserList) {
                FySystemOrganization fySystemOrganization = fySystemOrganizationService.findById(fySystemUser.getOrgId());
                fySystemUser.setOrganization(fySystemOrganization);
            }
        }
        return Result.success(systemUserPage);
    }

    /**
     * 系统管理员分配角色接口
     *
     * @param systemUserAssignRolesVo 分配角色信息
     * @return 操作结果
     */
    @Override
    public Result<String> assignRoles(SystemUserAssignRolesVo systemUserAssignRolesVo) {
        if (systemUserAssignRolesVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long userId = systemUserAssignRolesVo.getUserId();
        if (userId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        if (fySystemUser == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
        }
        List<FySystemUserRole> userRoleList = fySystemUserRoleService.selectByUserId(userId);
        if (!CollectionUtils.isEmpty(userRoleList)) {
            //删除原有角色
            int rows = fySystemUserRoleService.deleteByUserId(userId);
            if (rows <= 0) {
                return Result.getResult(ResultCodeEnum.DELETE_USER_ROLES_EXCEPTION);
            }
        }
        String roleIds = systemUserAssignRolesVo.getRoleIds();
        if (StringUtils.isBlank(roleIds)) {
            log.warn("FySystemUserServiceImpl assignRoles roleIds size = 0");
            return Result.success();
        }
        List<Long> ids = new ArrayList<>();
        Arrays.asList(roleIds.split(StringPool.COMMA)).forEach(id -> ids.add(Long.valueOf(id)));
        //新增角色
        int saveRows = fySystemUserRoleService.saveUserRoles(userId, ids);
        if (saveRows <= 0) {
            return Result.getResult(ResultCodeEnum.ADD_USER_ROLES_EXCEPTION);
        }
        return Result.success();
    }

    /**
     * 系统管理员状态修改接口
     *
     * @param systemUserStatusUpdateVo 系统管理员状态编辑参数
     * @return 操作结果
     */
    @Override
    public Result<String> updateStatus(SystemUserStatusUpdateVo systemUserStatusUpdateVo) {
        if (systemUserStatusUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long[] userIds = systemUserStatusUpdateVo.getUserIds();
        if (userIds == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        for (Long userId : userIds) {
            FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
            if (fySystemUser == null) {
                return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
            }
            String userStatus = systemUserStatusUpdateVo.getUserStatus();
            if (StringUtils.isBlank(userStatus)) {
                return Result.getResult(ResultCodeEnum.SYSTEM_USER_STATUS_NOT_NULL);
            }
            //如果是停用则删除用户和角色关联关系
            if(Constants.Status.DISABLE.equals(userStatus)){
                fySystemUserRoleService.deleteByUserId(userId);
            }
            fySystemUser.setUserStatus(userStatus);
            int rows = fySystemUserMapper.updateById(fySystemUser);
            if (rows <= 0) {
                return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
            }
        }
        return Result.success();
    }

    /**
     * 更新管理员账号最后登录时间
     *
     * @param fySystemUser 管理员信息
     */
    @Override
    public void updateLastLoginTime(FySystemUser fySystemUser) {
        fySystemUserMapper.updateLastLoginTime(DateUtil.getNowDate(), fySystemUser.getUserId());
    }

    /**
     * 系统管理员用户名校验接口
     *
     * @param userName 管理员用户名
     * @param userId   管理员ID
     * @return 校验结果
     */
    @Override
    public Result<String> userNameCheck(String userName, Long userId) {
        if (StringUtils.isBlank(userName)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NAME_NOT_NULL);
        }
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getUserName, userName);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemUser> systemUserByUserName = fySystemUserMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemUserByUserName)) {
            if (userId == null) {
                //新增
                return Result.success(ResultCodeEnum.SYSTEM_USER_NAME_EXIST.getMsg());
            } else {
                //编辑
                for (FySystemUser systemUser : systemUserByUserName) {
                    if (userId.longValue() != systemUser.getUserId().longValue()) {
                        return Result.success(ResultCodeEnum.SYSTEM_USER_NAME_EXIST.getMsg());
                    }
                }
            }
        }
        return Result.success();
    }

    /**
     * 系统管理员手机号校验接口
     *
     * @param mobile 管理员手机号
     * @param userId 管理员ID
     * @return 校验结果
     */
    @Override
    public Result<String> mobileCheck(String mobile, Long userId) {
        if (StringUtils.isBlank(mobile)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_MOBILE_NOT_NULL);
        }
        if (userId != null) {
            //编辑，脱敏后数据
            FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
            String sensitiveEncrypt = SensitiveEncryptUtil.sensitiveEncrypt(fySystemUser.getMobile(), SensitiveTypeEnum.MOBILE);
            if (mobile.equals(sensitiveEncrypt)) {
                return Result.success();
            }
        }
        boolean checkMobile = CommonVerifyUtil.checkMobile(mobile);
        if (!checkMobile) {
            return Result.getResult(ResultCodeEnum.SYSTEM_MOBILE_WRONGFUL);
        }
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getMobile, mobile);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemUser> systemUserByMobile = fySystemUserMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemUserByMobile)) {
            if (userId == null) {
                //新增
                return Result.success(ResultCodeEnum.SYSTEM_MOBILE_EXIST.getMsg());
            } else {
                //编辑
                for (FySystemUser systemUser : systemUserByMobile) {
                    if (userId.longValue() != systemUser.getUserId().longValue()) {
                        return Result.success(ResultCodeEnum.SYSTEM_MOBILE_EXIST.getMsg());
                    }
                }
            }
        }
        return Result.success();
    }

    /**
     * 系统管理员邮箱校验接口
     *
     * @param email  管理员邮箱
     * @param userId 管理员ID
     * @return 校验结果
     */
    @Override
    public Result<String> emailCheck(String email, Long userId) {
        if (StringUtils.isBlank(email)) {
            return Result.success();
        }
        if (userId != null) {
            //编辑，脱敏后数据
            FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
            String sensitiveEncrypt = SensitiveEncryptUtil.sensitiveEncrypt(fySystemUser.getEmail(), SensitiveTypeEnum.EMAIL);
            if (email.equals(sensitiveEncrypt)) {
                return Result.success();
            }
        }
        boolean checkEmail = CommonVerifyUtil.checkEmail(email);
        if (!checkEmail) {
            return Result.getResult(ResultCodeEnum.SYSTEM_EMAIL_WRONGFUL);
        }
        return Result.success();
    }

    /**
     * 获取系统管理员已选角色接口
     *
     * @param userId 管理员ID
     * @return 查询结果
     */
    @Override
    public Result<List<Long>> getUserRoles(Long userId) {
        List<FySystemUserRole> fySystemUserRoles = fySystemUserRoleService.selectByUserId(userId);
        List<Long> selectRoleIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(fySystemUserRoles)) {
            selectRoleIds = fySystemUserRoles.stream().map(FySystemUserRole::getRoleId).collect(Collectors.toList());
        }
        return Result.success(selectRoleIds);
    }

    /**
     * 登录用户密码强度校验接口
     *
     * @return 校验结果
     */
    @Override
    public Result<Integer> passwordStrengthCheck() {
        int mode = 0;
        Long userId = JwtTokenUtil.getLoginUser().getFySystemUser().getUserId();
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        String loginPwd = fySystemUser.getLoginPwd();
        if (StringUtils.isBlank(loginPwd)) {
            return Result.success("操作成功", mode);
        }
        loginPwd = Sm2Util.decryptData(loginPwd);
        if (loginPwd.length() < 8) {
            return Result.success("操作成功", mode);
        }
        String numberRegex = ".*[0-9].*";
        Pattern numberPattern = Pattern.compile(numberRegex);
        Matcher numberMatcher = numberPattern.matcher(loginPwd);
        if (numberMatcher.matches()) {
            mode++;
        }
        String lowercaseCharRegex = ".*[a-z].*";
        Pattern lowercaseCharPattern = Pattern.compile(lowercaseCharRegex);
        Matcher lowercaseCharMatcher = lowercaseCharPattern.matcher(loginPwd);
        String uppercaseCharRegex = ".*[A-Z].*";
        Pattern uppercaseCharPattern = Pattern.compile(uppercaseCharRegex);
        Matcher uppercaseCharMatcher = uppercaseCharPattern.matcher(loginPwd);
        if (lowercaseCharMatcher.matches() || uppercaseCharMatcher.matches()) {
            mode++;
        }
        if (lowercaseCharMatcher.matches() && uppercaseCharMatcher.matches()) {
            mode++;
        }
        return Result.success("操作成功", mode);
    }

    /**
     * 登录用户密码校验接口
     *
     * @return 校验结果
     */
    @Override
    public Result<String> passwordCheck(String loginPwd) {
        if (StringUtils.isBlank(loginPwd)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_LOGIN_PWD_NOT_NULL);
        }
        Long userId = JwtTokenUtil.getLoginUser().getFySystemUser().getUserId();
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        String dbLoginPwd = fySystemUser.getLoginPwd();
        if (StringUtils.isBlank(dbLoginPwd)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DB_LOGIN_PWD_EXCEPTION);
        }
        String msg = "";
        dbLoginPwd = Sm2Util.decryptData(dbLoginPwd);
        if (!loginPwd.equals(dbLoginPwd)) {
            msg = ResultCodeEnum.PASSWORD_ERROR.getMsg();
        }
        return Result.success(msg);
    }

    /**
     * 系统管理员密码修改接口
     *
     * @param systemLoginPwdUpdateVo 系统管理员密码编辑参数
     * @return 操作结果
     */
    @Override
    public Result<FySystemUser> updatePwd(SystemLoginPwdUpdateVo systemLoginPwdUpdateVo) {
        if (systemLoginPwdUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        String oldLoginPwd = systemLoginPwdUpdateVo.getOldLoginPwd();
        if (StringUtils.isBlank(oldLoginPwd)) {
            return Result.getResult(ResultCodeEnum.USER_OLD_LOGIN_PWD_NOT_NULL);
        }
        String newLoginPwd = systemLoginPwdUpdateVo.getNewLoginPwd();
        if (StringUtils.isBlank(newLoginPwd)) {
            return Result.getResult(ResultCodeEnum.USER_NEW_LOGIN_PWD_NOT_NULL);
        }
        if (oldLoginPwd.equals(newLoginPwd)) {
            return Result.getResult(ResultCodeEnum.USER_NEW_OLD_LOGIN_PWD_SAME);
        }
        Long userId = JwtTokenUtil.getLoginUser().getFySystemUser().getUserId();
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        String dbLoginPwd = fySystemUser.getLoginPwd();
        if (StringUtils.isBlank(dbLoginPwd)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DB_LOGIN_PWD_EXCEPTION);
        }
        dbLoginPwd = Sm2Util.decryptData(dbLoginPwd);
        if (!oldLoginPwd.equals(dbLoginPwd)) {
            return Result.getResult(ResultCodeEnum.PASSWORD_ERROR);
        }
        fySystemUser.setLoginPwd(newLoginPwd);
        int rows = fySystemUserMapper.updateById(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        return Result.success(fySystemUser);
    }

    /**
     * 系统账号手机号修改接口
     *
     * @param systemUserMobileUpdateVo 系统账号手机号编辑参数
     * @return 操作结果
     */
    @Override
    public Result<FySystemUser> updateMobile(SystemUserMobileUpdateVo systemUserMobileUpdateVo) {
        if (systemUserMobileUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        String mobile = systemUserMobileUpdateVo.getMobile();
        if (StringUtils.isBlank(mobile)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_MOBILE_NOT_NULL);
        }
        String newMobile = systemUserMobileUpdateVo.getNewMobile();
        if (StringUtils.isBlank(newMobile)) {
            return Result.getResult(ResultCodeEnum.USER_NEW_MOBILE_NOT_NULL);
        }
        boolean checkMobile = CommonVerifyUtil.checkMobile(newMobile);
        if (!checkMobile) {
            return Result.getResult(ResultCodeEnum.SYSTEM_MOBILE_WRONGFUL);
        }
        LoginUser loginUser = JwtTokenUtil.getLoginUser();
        Long userId = loginUser.getFySystemUser().getUserId();
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        fySystemUser.setMobile(newMobile);
        int rows = fySystemUserMapper.updateById(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        loginUser.setFySystemUser(fySystemUser);
        RedisUtil.set(JwtTokenUtil.getUserKey(), loginUser);
        return Result.success(fySystemUser);
    }

    /**
     * 系统账号邮箱修改接口
     *
     * @param systemUserEmailUpdateVo 系统账号邮箱编辑参数
     * @return 操作结果
     */
    @Override
    public Result<FySystemUser> updateEmail(SystemUserEmailUpdateVo systemUserEmailUpdateVo) {
        if (systemUserEmailUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        String newEmail = systemUserEmailUpdateVo.getNewEmail();
        if (StringUtils.isBlank(newEmail)) {
            return Result.getResult(ResultCodeEnum.USER_NEW_EMAIL_NOT_NULL);
        }
        boolean checkEmail = CommonVerifyUtil.checkEmail(newEmail);
        if (!checkEmail) {
            return Result.getResult(ResultCodeEnum.SYSTEM_EMAIL_WRONGFUL);
        }
        LoginUser loginUser = JwtTokenUtil.getLoginUser();
        Long userId = loginUser.getFySystemUser().getUserId();
        FySystemUser fySystemUser = fySystemUserMapper.selectById(userId);
        fySystemUser.setEmail(newEmail);
        int rows = fySystemUserMapper.updateById(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        loginUser.setFySystemUser(fySystemUser);
        RedisUtil.set(JwtTokenUtil.getUserKey(), loginUser);
        return Result.success(fySystemUser);
    }

    /**
     * 系统账号个人信息修改接口
     *
     * @param fySystemUser 系统账号个人信息编辑参数
     * @return 操作结果
     */
    @Override
    public Result<FySystemUser> updateUserInfo(FySystemUser fySystemUser) {
        if (fySystemUser == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long userId = fySystemUser.getUserId();
        if (userId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemUser systemUser = fySystemUserMapper.selectById(userId);
        if (systemUser == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
        }
        int rows = fySystemUserMapper.updateById(fySystemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        return Result.success(fySystemUser);
    }

    /**
     * 系统管理员重置密码接口
     *
     * @param userId 管理员ID
     * @return 操作结果
     */
    @Override
    public Result<String> resetPassword(Long userId) {
        if (userId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemUser systemUser = fySystemUserMapper.selectById(userId);
        if (systemUser == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_USER_NOT_FOUND);
        }
        String specialChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(specialChars.length());
            builder.append(specialChars.charAt(index));
        }
        systemUser.setLoginPwd(Sm2Util.decryptData(builder.toString()));
        int rows = fySystemUserMapper.updateById(systemUser);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        //TODO 短信通知新密码
        return Result.success();
    }

    /**
     * 获取所有可用用户
     *
     * @return 用户列表
     */
    @Override
    public List<FySystemUser> getAllUsableUser() {
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getUserStatus, Constants.Status.ENABLE);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        return fySystemUserMapper.selectList(queryWrapper);
    }

    /**
     * 通过组织机构ID获取用户列表
     *
     * @param orgId 组织机构ID
     * @return 用户列表
     */
    @Override
    public List<FySystemUser> findUserByOrgId(Long orgId) {
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getOrgId, orgId);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        return fySystemUserMapper.selectList(queryWrapper);
    }

    /**
     * 根据组织机构ID获取用户列表
     *
     * @param orgIdList 组织机构ID
     * @return 用户列表
     */
    @Override
    public List<FySystemUser> findUserByOrgIds(Set<Long> orgIdList) {
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(FySystemUser::getOrgId, orgIdList);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        return fySystemUserMapper.selectList(queryWrapper);
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public FySystemUser findUserById(Long userId) {
        return fySystemUserMapper.selectById(userId);
    }

    /**
     * 通过用户ID列表查询用户信息列表
     *
     * @param userIds 用户ID列表
     * @return 用户信息列表
     */
    @Override
    public List<FySystemUser> findUserByIds(List<Long> userIds) {
        return fySystemUserMapper.selectBatchIds(userIds);
    }

    /**
     * 获取用户菜单列表接口
     *
     * @return 菜单列表
     */
    @Override
    public Result<List<FySystemMenu>> getUserMenuList() {
        List<FySystemMenu> systemMenuList = JwtTokenUtil.getLoginUser().getSystemMenuList();
        if (!CollectionUtils.isEmpty(systemMenuList)) {
            systemMenuList = systemMenuList.stream().filter(fySystemMenu -> Constants.MENU_TYPE_MENU.equals(fySystemMenu.getMenuType())).collect(Collectors.toList());
        }
        return Result.success(systemMenuList);
    }

    private ResultCodeEnum checkUserParam(FySystemUser fySystemUser) {
        Long userId = fySystemUser.getUserId();
        String userName = fySystemUser.getUserName();
        if (StringUtils.isBlank(userName)) {
            return ResultCodeEnum.SYSTEM_USER_NAME_NOT_NULL;
        }
        LambdaQueryWrapper<FySystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemUser::getUserName, userName);
        queryWrapper.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemUser> systemUserByUserName = fySystemUserMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemUserByUserName)) {
            if (userId == null) {
                //新增
                return ResultCodeEnum.SYSTEM_USER_NAME_EXIST;
            }
            //编辑
            boolean isExist = systemUserByUserName.stream().allMatch(systemUser -> systemUser.getUserId().longValue() != userId.longValue());
            if (isExist) {
                return ResultCodeEnum.SYSTEM_USER_NAME_EXIST;
            }
        }
        String mobile = fySystemUser.getMobile();
        if (StringUtils.isBlank(mobile)) {
            return ResultCodeEnum.SYSTEM_MOBILE_NOT_NULL;
        }
        String email = fySystemUser.getEmail();
        if (userId == null) {
            String loginPwd = fySystemUser.getLoginPwd();
            if (StringUtils.isBlank(loginPwd)) {
                return ResultCodeEnum.SYSTEM_LOGIN_PWD_NOT_NULL;
            }
            LambdaQueryWrapper<FySystemUser> queryWrapperMobile = new LambdaQueryWrapper<>();
            queryWrapperMobile.eq(FySystemUser::getMobile, mobile);
            queryWrapperMobile.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
            List<FySystemUser> systemUserByMobile = fySystemUserMapper.selectList(queryWrapperMobile);
            if (!CollectionUtils.isEmpty(systemUserByMobile)) {
                return ResultCodeEnum.SYSTEM_USER_NAME_EXIST;
            }
            if (StringUtils.isNotBlank(email)) {
                boolean checkEmail = CommonVerifyUtil.checkEmail(email);
                if (!checkEmail) {
                    return ResultCodeEnum.SYSTEM_EMAIL_WRONGFUL;
                }
            }
        } else {
            FySystemUser systemUser = fySystemUserMapper.selectById(userId);
            String sensitiveMobile = SensitiveEncryptUtil.sensitiveEncrypt(systemUser.getMobile(), SensitiveTypeEnum.MOBILE);
            if (mobile.equals(sensitiveMobile)) {
                fySystemUser.setMobile(systemUser.getMobile());
            } else {
                boolean checkMobile = CommonVerifyUtil.checkMobile(mobile);
                if (!checkMobile) {
                    return ResultCodeEnum.SYSTEM_MOBILE_WRONGFUL;
                }
                LambdaQueryWrapper<FySystemUser> queryWrapperMobile = new LambdaQueryWrapper<>();
                queryWrapperMobile.eq(FySystemUser::getMobile, mobile);
                queryWrapperMobile.eq(FySystemUser::getDeleteFlag, Constants.DeleteFlag.NORMAL);
                List<FySystemUser> systemUserByMobile = fySystemUserMapper.selectList(queryWrapperMobile);
                if (!CollectionUtils.isEmpty(systemUserByMobile) && systemUserByMobile.stream().allMatch(systemUser1 -> systemUser1.getUserId().longValue() != userId.longValue())) {
                    return ResultCodeEnum.SYSTEM_USER_NAME_EXIST;
                }
            }
            String sensitiveName = SensitiveEncryptUtil.sensitiveEncrypt(systemUser.getRealName(), SensitiveTypeEnum.NAME);
            if (StringUtils.isNotBlank(sensitiveName) && sensitiveName.equals(fySystemUser.getRealName())) {
                fySystemUser.setRealName(systemUser.getRealName());
            }
            String sensitiveEmail = SensitiveEncryptUtil.sensitiveEncrypt(systemUser.getEmail(), SensitiveTypeEnum.EMAIL);
            if (sensitiveEmail.equals(fySystemUser.getEmail())) {
                fySystemUser.setRealName(systemUser.getRealName());
            } else {
                boolean checkEmail = CommonVerifyUtil.checkEmail(email);
                if (!checkEmail) {
                    return ResultCodeEnum.SYSTEM_EMAIL_WRONGFUL;
                }
            }
        }
        String userStatus = fySystemUser.getUserStatus();
        if (userId == null && StringUtils.isBlank(userStatus)) {
            fySystemUser.setUserStatus(Constants.Status.ENABLE);
        }
        String dataPermissionRange = fySystemUser.getDataPermissionRange();
        if (StringUtils.isBlank(dataPermissionRange)) {
            fySystemUser.setDataPermissionRange(DataPermissionRangeEnum.PERSONAL_DATA.getType());
        }
        return null;
    }
}
